import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

let userState = {
	userName: '',
	hasLogin: false, // 是否登录
	hasSkip: true   ,// 是否跳过启动页
	userType:''
};
let purchaseNumberList=new Array();
const purchaseNumber=uni.getStorageSync('purchaseNumber');
if(Object.prototype.toString.call(purchaseNumber) === '[object Object]'){
	purchaseNumberList=purchaseNumber
}
const userInfo = uni.getStorageSync('userInfo');
if(userInfo.hasLogin){	
	userState = userInfo;
}
if(userInfo.hasSkip){	// 用户已经跳过启动页，但是没有登录
	userState.hasSkip = true;
}
const store = new Vuex.Store({
    state: {
		...userState,
		purchaseNumberList
	},

    mutations: {
        login(state, user) {  // 用户登录
            state.userName = user.userName;
            state.hasLogin = true;
			state.userType = user.userType;
			console.log({...state})
			uni.setStorageSync('userInfo', {...state});	
        },
        logout(state) {			// 用户退出
            state.userName = "";
            state.hasLogin = false;
			state.userType = '';
			// todo: 当用户退出时，启动页可以不再显示
			uni.clearStorageSync();
        },
		changeLogo(state, img){	// 用户修改图片
			state.userImg = img;
			
			uni.setStorageSync('userInfo', {...state});	
		},
		skipIndex(state){	// 用户跳过首页
			state.hasSkip = true; 
			
			uni.setStorageSync('userInfo', {...state});	
		},
		show(state){
			console.log({...state});
		},
		changeCart(state,goods){
			let flag=false;
			let newList=[];
			for(var i=0;i<state.purchaseNumberList.length;i++){
				if(goods.goodsid==state.purchaseNumberList[i].goodsid){
					if(goods.purchasenum!=0){
						state.purchaseNumberList[i].purchasenum=goods.purchasenum;
					}else{
						state.purchaseNumberList.splice(i,1);
					}
					flag=true;
					break;
				}
			}
			if(!flag&&goods.purchasenum!=0){
				state.purchaseNumberList.push(goods);
			}
			console.log(state.purchaseNumberList);
			uni.setStorageSync('purchaseNumber',state.purchaseNumberList);
		},
		empty(state){
			state.purchaseNumberList=[]
			uni.setStorageSync('purchaseNumber',state.purchaseNumberList);
		}
    }
});

export default store
